package com.litorg.demo.db.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class HttpResponse extends HttpServletResponseWrapper {

	public HttpResponse(HttpServletResponse response) {
		super(response);
	}

	
	public void Error(int code , String message) {
		this.JSON(code, message);
	}
	
	
	/**
	 * 序列化JSON对象
	 */
	public void JSON(int code, Object body) {
	
		this.setHeader("content-type", "application/json");
		this.setCharacterEncoding("utf8");
		
		this.setStatus(code);
		ObjectMapper mapper = new ObjectMapper();

		try {
			mapper.writeValue(this.getWriter(), body);
		}catch(Exception ex) {
			this.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			try {
				this.getWriter().write("JSON序列化异常!");
			}catch(Exception e) {
				System.out.println("获取response的writer异常!");
				e.printStackTrace();
			}
		}
		
		return;
	}

}